package ua.net.gm.server.primitives;

import java.util.List;
import java.util.Random;

public class PointFactory
{
    private final Random rand;

    private static PointFactory instance;

    public PointFactory()
    {
        rand = new Random();
    }

    public PointFactory(Random rand)
    {
        this.rand = rand;
    }
    
    public static PointFactory getInstance()
    {
        if (instance == null)
        {
            instance = new PointFactory();
        }
        return instance;
    }

    /**
     * Create random point inside rectangle 
     * inclusive X1,Y1 and the exclusive X2,Y2
     * @param rect
     * @return point with random coordinate
     */
    public Point createRandomPoint(Rectangle rect)
    {
        return new Point(rect.getX() + rand.nextInt(rect.getWidth()),
                rect.getY() + rand.nextInt(rect.getWidth()));
    }
    
    /*
     * Create random point inside rectangle with minimum distance to existing in list
     */
    public Point createRandomPoint(List<Point> points, Rectangle rect, int minDistance, int tryCount)
    {
        Point res = null;
        do
        {
            res = createRandomPoint(rect);
            for (Point point : points)
            {
                if (res.distance(point) < minDistance)
                {
                    res = null;
                }
            }
            tryCount--;
        }
        while (res == null && tryCount > 0);
        return res;
    }
}
